import Vue from 'vue'
import VueRouter from 'vue-router'
import eventBus from 'ts-element/packages/utils/eventBus'
import { $get, $api } from 'ts-element/packages/utils/ajax'
import mModal from 'ts-element/packages/utils/confirm'
// 为了重复路由报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

function menuFn(menus) {
    for (let v of menus) { // 遍历路由
        let url = v.alink ? v.alink.split('?')[0] : ''
        if (url !== '#' && url !== '/') {
            let _dir = url
            if (url.indexOf('_') > -1) {
                _dir = url.split('_')[0]
            }
            if (v.alink.indexOf('selfIframe') == -1) {
                const d = {
                    name: v.id,
                    path: url,
                    component: resolve => require(['@/views' + _dir], resolve),
                    props: true,
                    meta: {
                        title: v.menuname, //页面标题
                        canMultipleOpen: true //支持根据参数不同多开不同页签
                    }
                }
                if (v.redirect !== undefined) {
                    d.redirect = v.redirect
                }
                menuRouters.push(d)
            }
        }
        if (v.menus && v.menus.length > 0) {
            menuFn(v.menus)
        }
    }
}

Vue.use(VueRouter)
let routes = []
let menuRouters = []
// 获取非乾坤模式下的菜单
async function getfmenus(router) {
    global.appLoading = true
    let response = await $get('/ts-system/menu/getfmenus?syscode=design')
    global.appLoading = false
    eventBus.$emit('changeAppLoading', false)
    const obj = response.object || []
    window.logoTitle = obj.length > 0 ? obj[0].menuname : window.logoTitle // 获取系统名称
    if (!global.resource && !global.userInfo) { //判断第一次进来,且非乾坤模式下
        getUserInfo()
    }
    if (response.success) {
        // 获取整理后菜单及路由
        menuFn(obj[0].menus)
    }
    if (!localStorage.getItem('token')) {
        localStorage.setItem('token', global.userInfo.token)
    }
    router.addRoutes(menuRouters)
    global.router = menuRouters
}

async function getUserInfo() {
    let res = await $get('/ts-system/user/info')
    if (res.success) {
        global.userInfo = res.object
        if (!global.resource) {
            getMenuResource()
        }
    }
}
// 获取资源id池
async function getMenuResource() {
    let res = await $get('/ts-system/resource/getMenuResourceBySyscode/' + (window.syscode || 'design'))
    global.resource = res.object
    sessionStorage.setItem('resource', JSON.stringify(global.resource || []))
}
/**@desc **/
export const getRouter = function (props, qkRouters) {
    let base = '';
    if (window.__POWERED_BY_QIANKUN__) {
        base = props.data.activeRule || '/';
    } else { // 非乾坤
        base = process.env.BASE_URL
        routes = [
        // {
        //     path: '/biEditor',
        //     name: 'biEditor',
        //     component: () =>
        //         import('@/views/biEditor.vue')
        // }, 
            {
                path: '/',
                name: 'index',
                component: () => import('@/views/helloword.vue')
            },
            {
                path: '/wzhIndex',
                name: 'index',
                component: () => import('@/views/helloword.vue')
            },
            {
                path: '/selfIframe',
                name: 'selfIframe',
                component: () => import('@/views/selfIframe.vue')
            }
        ]
    }
    const router = new VueRouter({
        base,
        mode: window.__POWERED_BY_QIANKUN__ ? 'history' : 'hash',
        // mode: "history",
        routes
    });
    if (qkRouters) {
        router.addRoutes(qkRouters)
        global.router = qkRouters
    } else {
        if (!global.resource && !global.router && !global.userInfo && !window.__POWERED_BY_QIANKUN__) { //判断第一次进来,且非乾坤模式下
            getfmenus(router)
        }
    }


    router.beforeEach(async function (to, from, next) {
        global.menuId = to.name || '' // 保存此次菜单
        global.software = to.fullPath.indexOf('software') > -1 ? 'bs' : ''
        if (to.path) { // 动态加载路由
            if (!global.router) {
                global.router = []
            }
            let index = global.router.findIndex(res => res.name == to.path || res.path == to.path)
            if (index == -1) { // 不存在路由,则注册路由
                let d = {
                    name: to.path,
                    path: to.path,
                    component: null,
                    props: true,
                    meta: {
                        // title: v.menuname, //页面标题
                        canMultipleOpen: true //支持根据参数不同多开不同页签
                    }
                }
                
                let routerUrl = to.path.split('_')[0]
                if(routerUrl === '/') {
                    d.component = () => import('@/views/helloword.vue')
                } else {
                    d.component = () => import(`@/views${routerUrl}.vue`)
                }
                global.router.push(d)
                router.addRoute(d)
                next(to)
            }
        }
        // console.log('$$$', to, from)
        // if (
        //     from && from.query && from.query.url &&
        //     from.query.url.indexOf('#/framework') > -1
        // ) {
        //     debugger
        //     // 低代码设计器中退出
        //     await mModal.confirm('当前页面数据未保存，确认离开').then(async type => {
        //         if (type === 'confirm') {
        //             next()
        //         }
        //     })
        //     next(false)
        // } else {
        next()
        // }
    })
    return router;
};

